package jwt.lab02;

import javax.mail.*;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Utils {

    public static final String PROPERTIES_FILE = "jwt/lab02/mail.properties";

    public static Properties loadProperties(String fileName) {
        Properties props = null;

        try {
            InputStream propertiesStream = Utils.class.getClassLoader().getResourceAsStream(fileName);
            if (propertiesStream == null)
                propertiesStream = new FileInputStream(fileName);

            props = new Properties();
            props.load(propertiesStream);
        } catch (IOException e) {
            System.err.println("Properties file not load (file: " + fileName + ")");
        }

        return props;
    }

    public static String messageToString(Message msg) throws MessagingException {
        StringBuffer sb = new StringBuffer();
        sb.append("From: ");
        for (Address address : msg.getFrom()) {
            sb.append(normalizeString(address.toString()));
            sb.append(" ");
        }
        sb.append("  Subject: ");
        sb.append(normalizeString(msg.getSubject()));
        return sb.toString();
    }

    public static String normalizeString(String txt) {
        if (txt.startsWith("=?UTF-8?Q?"))
            return txt.substring(10, txt.length()).replaceAll("\\?=", "");
        return txt;
    }

    public static Message[] getAllMessages(String popServer, String popUser, String popPass) throws MessagingException, IOException {
        System.out.println("Checking mail...");
        Properties props = new Properties();
        props.put("mail.store.protocol", "pop3");
        props.put("mail.pop3.host", popServer);
        props.put("mail.pop3.user", popUser);
        props.put("mail.pop3.password", popPass);

        Session session = Session.getDefaultInstance(props, null);

        Store store = session.getStore(props.getProperty("mail.store.protocol"));
        store.connect(props.getProperty("mail.pop3.host"), props.getProperty("mail.pop3.user"), props.getProperty("mail.pop3.password"));

        Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);

        Message message[] = folder.getMessages();

        for (int i = 0, n = message.length; i < n; i++)
            message[i].getContent();

        folder.close(false);
        store.close();

        return message;
    }

    public static String messagesToString(Message[] messages) throws MessagingException {
        StringBuffer sb = new StringBuffer();

        for (int i = 0, n = messages.length; i < n; i++)
            sb.append(i + ": " + Utils.messageToString(messages[i]) + "\n");

        return sb.toString();
    }

}
